package cate.game.server.cli;

import cate.game.client.msg.GameMsg;
import easy.java.codec.ZlibCodec;
import easy.socket.util.BBU;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class MsgDecode {

    public static GameMsg decode(BinaryWebSocketFrame frame, ChannelHandlerContext ctx) {
        GameMsg msg = new GameMsg();
        ByteBuf buf = frame.content();
        msg.idA = buf.readInt();
        msg.idB = buf.readInt();
        msg.srvId = buf.readInt();
        msg.codec = buf.readByte();
        log.debug("recv a={}, b={}, srvId={}, codec={}", msg.idA, msg.idB, msg.srvId, msg.codec);
        switch(msg.codec) {
            case GameMsg.CODEC_JSON:
                msg.contentBytes = BBU.readAutoBytes(buf);
                break;
            case GameMsg.CODEC_JSON_ZIP:
                byte[] bytes = BBU.readAutoBytes(buf);
                msg.contentBytes = ZlibCodec.instance().uncompress(bytes);
                break;
        }
        msg.context = new NettyContextImpl(ctx);
        return msg;
    }
}
